//------------------------------------------------------------------------
// Abstract: Implement of class Console
//
// Authoring: XiaoHanxiong
//
// Time: 2013.12.08
//
// Static test:
//
// Version history:
//		Ver_1.0	: 2013.12.08	XiaoHanxiong
//		Ver_1.1 : 2013.12.30	XiaoHanxiong
//------------------------------------------------------------------------
#include "Console.h"


namespace Library
{
	ofstream Console::log_file;
	ofstream Console::error_file;
	bool Console::log_flag = false;
	bool Console::error_flag = false;
	bool Console::time_flag = false;
	bool Console::init_flag = false;

	Console::Console()
	{

	}

	Console::~Console()
	{
		// Release *.txt files
		if(error_flag)
		{
			error_file.close();
		}
		if(log_flag)
		{
			log_file.close();
		}
	}

	void Console::Initialize( string log_fname, string error_fname )
	{
		// Initialize only once
		if(!init_flag)
		{
			log_file.open(log_fname, ios::out);
			error_file.open(error_fname, ios::out);

			if(log_file) Console::log_flag = true;
			if(error_file) Console::error_flag = true;
			Console::time_flag = true;
			Console::init_flag = true;
		}
	}

	void Console::Error( char* fmt, ... )
	{
		va_list args;
		static char buf[1024];
		int n;
		char time[30];

		va_start(args, fmt);
		n = vsprintf(buf, fmt, args);
		va_end(args);

		SetColor(RED);
		GetTime(time);
		Stdout << time << buf << endl;
		if(error_flag)
		{
			error_file << time << buf << endl;
		}
	}

	void Console::Log( char* fmt, ... )
	{
		va_list args;
		static char buf[1024];
		int n;
		char time[30];

		va_start(args, fmt);
		n = vsprintf(buf, fmt, args);
		va_end(args);

		SetColor(WHITE);
		GetTime(time);
		Stdout << time << buf << endl;
		if(log_flag)
		{
			log_file << time << buf << endl;
		}
	}

	void Console::SetColor( int color )
	{
		HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

		if(color >= 0x000 && color <= 0x0007)
		{
			SetConsoleTextAttribute(hStdout, color);
		}
		else
		{
			SetConsoleTextAttribute(hStdout, 0x0007);
		}
	}

	void Console::GetTime( char* buf )
	{
		time_t nowtime;
		struct tm *local;

		if(time_flag)
		{
			nowtime = time(NULL);
			local = localtime(&nowtime);
			strftime(buf, 30, "[%Y-%m-%d %H:%M:%S] ",local);
		}
		else
		{
			memset(buf, 0, 30);
		}
	}

	void Console::SetTimeFlag( bool flag )
	{
		time_flag = flag;
	}
}



LIBRARY_END